<template>
  <div class="admin-billing-container">
    <div class="page-header">
      <div class="header-title">
        <h2>荣誉管理</h2>
        <span class="header-desc">查看和管理系统订单账单信息</span>
      </div>
      <div class="header-actions">
        <el-button type="primary" icon="el-icon-download" @click="handleExportOrders">导出订单数据</el-button>
      </div>
    </div>

    <!-- 统计信息卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :span="6">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="statistics-icon orders-icon">
              <i class="el-icon-s-order"></i>
            </div>
            <div class="statistics-info">
              <div class="statistics-title">总订单数</div>
              <div class="statistics-value">{{ statisticsData.totalOrders || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="statistics-icon revenue-icon">
              <i class="el-icon-money"></i>
            </div>
            <div class="statistics-info">
              <div class="statistics-title">总收入</div>
              <div class="statistics-value">¥ {{ formatPrice(statisticsData.totalRevenue || 0) }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="statistics-icon completed-icon">
              <i class="el-icon-circle-check"></i>
            </div>
            <div class="statistics-info">
              <div class="statistics-title">已付款订单</div>
              <div class="statistics-value">{{ statisticsData.completedOrders || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="statistics-card">
          <div class="statistics-item">
            <div class="statistics-icon pending-icon">
              <i class="el-icon-time"></i>
            </div>
            <div class="statistics-info">
              <div class="statistics-title">待付款订单</div>
              <div class="statistics-value">{{ statisticsData.pendingOrders || 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.status" placeholder="全部状态" clearable>
            <el-option label="全部状态" value=""></el-option>
            <el-option label="待付款" value="0"></el-option>
            <el-option label="待发货" value="1"></el-option>
            <el-option label="待收货" value="2"></el-option>
            <el-option label="已完成" value="3"></el-option>
            <el-option label="已取消" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateRangeChange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="queryParams.orderNumber" placeholder="请输入订单编号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="table-card">
      <div class="table-operations" v-if="selectedOrders.length > 0">
        <span class="selected-count">已选择 {{ selectedOrders.length }} 个订单</span>
        <el-button size="small" type="danger" icon="el-icon-delete" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <el-table
        :data="orderList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="订单ID" width="80" align="center"></el-table-column>
        <el-table-column prop="orderNo" label="订单编号" min-width="120"></el-table-column>
        <el-table-column label="用户信息" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.username || '用户' + scope.row.userId }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="120" align="right">
          <template slot-scope="scope">
            ¥ {{ formatPrice(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-view"
              @click="handleViewDetail(scope.row)"
              circle
              title="查看详情"
            ></el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-edit"
              @click="handleChangeStatus(scope.row)"
              circle
              title="修改状态"
            ></el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              circle
              title="删除订单"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="queryParams.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size.sync="queryParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="detailDialogVisible" width="70%" class="detail-dialog">
      <div v-loading="detailLoading">
        <div class="detail-header">
          <div class="detail-title">
            <h3>订单号：{{ orderDetail.orderNo }}</h3>
          </div>
          <el-tag :type="getStatusType(orderDetail.status)">{{ getStatusText(orderDetail.status) }}</el-tag>
        </div>

        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20" class="detail-info">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">订单ID：</span>
              <span class="value">{{ orderDetail.id }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">用户名：</span>
              <span class="value">{{ orderDetail.username || '用户' + orderDetail.userId }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">用户ID：</span>
              <span class="value">{{ orderDetail.userId }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">订单金额：</span>
              <span class="value price">¥ {{ formatPrice(orderDetail.totalAmount) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ formatDateTime(orderDetail.createTime) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">支付时间：</span>
              <span class="value">{{ orderDetail.payTime ? formatDateTime(orderDetail.payTime) : '未支付' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">收货信息</el-divider>
        
        <el-row :gutter="20" class="detail-info">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">收货人：</span>
              <span class="value">{{ orderDetail.receiverName || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">联系电话：</span>
              <span class="value">{{ orderDetail.receiverPhone || '--' }}</span>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="detail-item">
              <span class="label">收货地址：</span>
              <span class="value">{{ orderDetail.receiverAddress || '--' }}</span>
            </div>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">订单商品</el-divider>
        
        <el-table :data="orderDetail.orderItems || []" border style="width: 100%">
          <el-table-column label="商品图片" width="100" align="center">
            <template slot-scope="scope">
              <el-image 
                style="width: 60px; height: 60px" 
                :src="scope.row.imageUrl || 'https://via.placeholder.com/60'" 
                fit="cover"
                :preview-src-list="[scope.row.imageUrl || 'https://via.placeholder.com/60']">
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="flowerId" label="花卉ID" width="80"></el-table-column>
          <el-table-column prop="flowerName" label="花卉名称" min-width="150"></el-table-column>
          <el-table-column prop="price" label="单价" width="100" align="right">
            <template slot-scope="scope">
              ¥ {{ formatPrice(scope.row.price) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80" align="center"></el-table-column>
          <el-table-column label="小计" width="120" align="right">
            <template slot-scope="scope">
              ¥ {{ formatPrice(scope.row.price * scope.row.quantity) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handlePrint">打印订单</el-button>
      </span>
    </el-dialog>

    <!-- 修改订单状态对话框 -->
    <el-dialog title="修改订单状态" :visible.sync="statusDialogVisible" width="30%">
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="订单编号">
          <span>{{ statusForm.orderNo }}</span>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(statusForm.currentStatus)">
            {{ getStatusText(statusForm.currentStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-select v-model="statusForm.newStatus" placeholder="请选择新状态">
            <el-option label="待付款" value="0"></el-option>
            <el-option label="待发货" value="1"></el-option>
            <el-option label="待收货" value="2"></el-option>
            <el-option label="已完成" value="3"></el-option>
            <el-option label="已取消" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="statusForm.remark" rows="3"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmChangeStatus">确定</el-button>
      </span>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="30%">
      <span>确定要删除该订单吗？此操作不可恢复！</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </span>
    </el-dialog>

    <!-- 批量删除确认对话框 -->
    <el-dialog
      title="批量删除"
      :visible.sync="batchDeleteDialogVisible"
      width="30%">
      <span>确定要删除选中的 {{ selectedOrders.length }} 个订单吗？此操作不可恢复！</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchDeleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmBatchDelete">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AdminBilling',
  data() {
    return {
      // 加载状态
      loading: false,
      detailLoading: false,
      
      // 订单列表数据
      orderList: [],
      total: 0,
      selectedOrders: [],
      
      // 查询参数
      queryParams: {
        status: '',
        orderNumber: '',
        page: 1,
        size: 10,
        startDate: '',
        endDate: ''
      },
      dateRange: [],
      
      // 统计数据
      statisticsData: {
        totalOrders: 0,
        totalRevenue: 0,
        completedOrders: 0,
        pendingOrders: 0
      },
      
      // 订单详情
      detailDialogVisible: false,
      orderDetail: {},
      
      // 状态修改
      statusDialogVisible: false,
      statusForm: {
        id: null,
        orderNo: '',
        currentStatus: '',
        newStatus: '',
        remark: ''
      },
      
      // 删除确认
      deleteDialogVisible: false,
      currentOrder: null,
      
      // 批量删除确认
      batchDeleteDialogVisible: false
    }
  },
  created() {
    this.getOrderList();
    this.getStatisticsData();
  },
  methods: {
    // 获取订单列表
    getOrderList() {
      this.loading = true;
      this.request.get('/orders/admin/list', { 
        params: this.queryParams 
      }).then(response => {
        // 处理后端返回的数据
        if (response.code === 1) {
          this.orderList = response.data || [];
          this.total = this.orderList.length; // 如果后端返回了总数，应该使用后端返回的总数
        } else {
          this.$message.error('获取订单数据失败：' + (response.msg || '未知错误'));
          this.orderList = [];
          this.total = 0;
        }
      }).catch(error => {
        console.error('Failed to fetch orders list:', error);
        this.$message.error('获取订单列表失败');
        this.orderList = [];
        this.total = 0;
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 获取统计数据
    getStatisticsData() {
      const params = {};
      if (this.queryParams.startDate) {
        params.startDate = this.queryParams.startDate;
      }
      if (this.queryParams.endDate) {
        params.endDate = this.queryParams.endDate;
      }
      
      this.request.get('/orders/admin/statistics', { 
        params: params 
      }).then(response => {
        if (response.code === 1) {
          const statsData = response.data || {};
          this.statisticsData = {
            totalOrders: statsData.totalOrders || 0,
            totalRevenue: statsData.totalAmount || 0,
            completedOrders: statsData.paidOrders || 0,
            pendingOrders: statsData.unpaidOrders || 0
          };
        } else {
          this.$message.error('获取统计数据失败：' + (response.msg || '未知错误'));
        }
      }).catch(error => {
        console.error('Failed to fetch statistics:', error);
        this.$message.error('获取统计数据失败');
      });
    },
    
    // 处理日期范围变化
    handleDateRangeChange(dates) {
      if (dates) {
        this.queryParams.startDate = dates[0];
        this.queryParams.endDate = dates[1];
      } else {
        this.queryParams.startDate = '';
        this.queryParams.endDate = '';
      }
    },
    
    // 查询订单
    handleQuery() {
      this.queryParams.page = 1;
      this.getOrderList();
      this.getStatisticsData();
    },
    
    // 重置查询条件
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        status: '',
        orderNumber: '',
        page: 1,
        size: 10,
        startDate: '',
        endDate: ''
      };
      this.getOrderList();
      this.getStatisticsData();
    },
    
    // 每页数量变化
    handleSizeChange(size) {
      this.queryParams.size = size;
      this.getOrderList();
    },
    
    // 当前页变化
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.getOrderList();
    },
    
    // 多选变化
    handleSelectionChange(selection) {
      this.selectedOrders = selection;
    },
    
    // 查看订单详情
    handleViewDetail(row) {
      this.detailLoading = true;
      this.detailDialogVisible = true;
      
      this.request.get(`/orders/admin/detail/${row.id}`).then(response => {
        if (response.code === 1) {
          this.orderDetail = response.data || {};
        } else {
          this.$message.error('获取订单详情失败：' + (response.msg || '未知错误'));
          this.orderDetail = {};
        }
      }).catch(error => {
        console.error('Failed to fetch order detail:', error);
        this.$message.error('获取订单详情失败');
        this.orderDetail = {};
      }).finally(() => {
        this.detailLoading = false;
      });
    },
    
    // 修改订单状态
    handleChangeStatus(row) {
      this.statusForm = {
        id: row.id,
        orderNo: row.orderNo,
        currentStatus: row.status,
        newStatus: '',
        remark: ''
      };
      this.statusDialogVisible = true;
    },
    
    // 确认修改状态
    confirmChangeStatus() {
      if (!this.statusForm.newStatus) {
        this.$message.warning('请选择新状态');
        return;
      }
      
      const params = {
        orderId: this.statusForm.id,
        status: this.statusForm.newStatus,
        remark: this.statusForm.remark
      };
      
      this.request.put('/orders/admin/updateStatus', params).then(response => {
        if (response.code === 1) {
          this.$message.success('订单状态修改成功');
          this.statusDialogVisible = false;
          // 刷新订单列表
          this.getOrderList();
        } else {
          this.$message.error('修改订单状态失败：' + (response.msg || '未知错误'));
        }
      }).catch(error => {
        console.error('Failed to update order status:', error);
        this.$message.error('修改订单状态失败');
      });
    },
    
    // 删除订单
    handleDelete(row) {
      this.currentOrder = row;
      this.deleteDialogVisible = true;
    },
    
    // 确认删除
    confirmDelete() {
      if (!this.currentOrder) return;
      
      this.request.delete(`/orders/admin/delete/${this.currentOrder.id}`).then(response => {
        if (response.code === 1) {
          this.$message.success('订单删除成功');
          this.getOrderList();
          this.getStatisticsData();
        } else {
          this.$message.error('删除订单失败：' + (response.msg || '未知错误'));
        }
      }).catch(error => {
        console.error('Failed to delete order:', error);
        this.$message.error('删除订单失败');
      }).finally(() => {
        this.deleteDialogVisible = false;
        this.currentOrder = null;
      });
    },
    
    // 批量删除
    handleBatchDelete() {
      if (this.selectedOrders.length === 0) {
        this.$message.warning('请至少选择一个订单');
        return;
      }
      this.batchDeleteDialogVisible = true;
    },
    
    // 确认批量删除
    confirmBatchDelete() {
      const orderIds = this.selectedOrders.map(item => item.id);
      
      this.request.delete('/orders/admin/batchDelete', {
        data: orderIds
      }).then(response => {
        if (response.code === 1) {
          this.$message.success('批量删除成功');
          this.getOrderList();
          this.getStatisticsData();
        } else {
          this.$message.error('批量删除失败：' + (response.msg || '未知错误'));
        }
      }).catch(error => {
        console.error('Failed to batch delete orders:', error);
        this.$message.error('批量删除失败');
      }).finally(() => {
        this.batchDeleteDialogVisible = false;
      });
    },
    
    // 导出订单数据
    handleExportOrders() {
      const params = {};
      if (this.queryParams.startDate) {
        params.startDate = this.queryParams.startDate;
      }
      if (this.queryParams.endDate) {
        params.endDate = this.queryParams.endDate;
      }
      
      // 创建一个临时链接用于下载
      const downloadUrl = this.request.defaults.baseURL + '/orders/admin/export?' + 
        Object.entries(params)
          .filter(([, v]) => v)  // 使用逗号表示忽略第一个参数
          .map(([k, v]) => `${k}=${v}`)
          .join('&');
      
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.setAttribute('download', '订单数据.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      this.$message.success('订单数据导出中...');
    },
    
    // 打印订单
    handlePrint() {
      window.print();
    },
    
    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: 'warning',  // 待付款
        1: 'primary',  // 待发货
        2: 'info',     // 待收货
        3: 'success',  // 已完成
        4: 'info',     // 已取消
      };
      return statusMap[status] || 'info';
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '待发货',
        2: '待收货',
        3: '已完成',
        4: '已取消',
      };
      return statusMap[status] || '未知状态';
    },
    
    // 格式化价格
    formatPrice(price) {
      return parseFloat(price || 0).toFixed(2);
    },
    
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '--';
      const date = new Date(dateTime);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    }
  }
}
</script>

<style scoped>
.admin-billing-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.header-desc {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.statistics-row {
  margin-bottom: 20px;
}

.statistics-card {
  margin-bottom: 15px;
  transition: all 0.3s;
}

.statistics-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.statistics-item {
  display: flex;
  align-items: center;
}

.statistics-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.statistics-icon i {
  font-size: 24px;
  color: #fff;
}

.orders-icon {
  background-color: #409EFF;
}

.revenue-icon {
  background-color: #67C23A;
}

.completed-icon {
  background-color: #E6A23C;
}

.pending-icon {
  background-color: #F56C6C;
}

.statistics-info {
  flex: 1;
}

.statistics-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.statistics-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.table-card {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.selected-count {
  margin-right: 15px;
  color: #606266;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.detail-title h3 {
  margin: 0;
  color: #303133;
}

.detail-info {
  margin-bottom: 20px;
}

.detail-item {
  margin-bottom: 10px;
  line-height: 1.5;
}

.detail-item .label {
  color: #909399;
  margin-right: 8px;
}

.detail-item .value {
  color: #303133;
  font-weight: 500;
}

.detail-item .value.price {
  color: #F56C6C;
  font-weight: bold;
}

@media print {
  .page-header, .filter-card, .table-card, .pagination-container, .el-dialog__footer {
    display: none !important;
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .detail-dialog {
    width: 100% !important;
    margin: 0 !important;
    top: 0 !important;
    left: 0 !important;
    position: relative !important;
    transform: none !important;
  }
}
</style>